import React, { useState, useRef } from 'react';
import './app.css';

export default function App() {
  const fileRef = useRef(null);
  const [imgPreview, setImgPreview] = useState('https://res.bearbobo.com/resource/upload/W44yyxvl/upload-ih56twxirei.png');
  const [imgUrl, setImgUrl] = useState(null); // 初始值为null而不是'null'
  const [status, setStatus] = useState(''); 

  // 更新预览图片
  const updateImageData = () => {
    const file = fileRef.current.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      setImgPreview(reader.result);
    };
  };

  // 表单状态
  const [uniform_number, setUniformNumber] = useState(10);
  const [uniform_color, setUniformColor] = useState('红');
  const [position, setPosition] = useState(0);
  const [shooting_hand, setShootingHand] = useState(1);
  const [style, setStyle] = useState('写实');

  // 环境变量
  const patToken = import.meta.env.VITE_PAT_TOKEN;
  const uploadUrl = 'https://api.coze.cn/v1/files/upload';
  const workflowUrl = 'https://api.coze.cn/v1/workflow/run';
  const workflow_id = '7536408051043237931';

  // 上传文件到Coze
  async function uploadFile() {
    try {
      const inputFile = fileRef.current.files[0];
      if (!inputFile) {
        throw new Error('请先选择文件');
      }

      const formData = new FormData();
      formData.append('file', inputFile);

      const res = await fetch(uploadUrl, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${patToken}`
        },
        body: formData
      });

      if (!res.ok) {
        throw new Error(`上传失败: ${res.status}`);
      }

      const ret = await res.json();
      if (ret.code !== 0) {
        throw new Error(ret.msg || '上传API返回错误');
      }

      return ret.data.id;
    } catch (error) {
      console.error('上传错误:', error);
      setStatus(`上传失败: ${error.message}`);
      return null;
    }
  }

  // 生成图片
  const generate = async () => {
    try {
      // 重置状态
      setImgUrl(null);
      setStatus('上传中...');

      // 上传文件
      const file_id = await uploadFile();
      if (!file_id) return;

      setStatus('生成中...');

      // 调用工作流
      const res = await fetch(workflowUrl, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${patToken}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          workflow_id,
          parameters: {
            picture: JSON.stringify({ file_id }),
            style,
            uniform_number: Number(uniform_number),
            uniform_color,
            position: Number(position),
            shooting_hand: Number(shooting_hand),
          }
        })
      });

      if (!res.ok) {
        throw new Error(`工作流调用失败: ${res.status}`);
      }

      const ret = await res.json();
      console.log('API响应:', ret); // 调试用

      if (ret.code !== 0) {
        throw new Error(ret.msg || '工作流返回错误');
      }

      // 解析响应数据
      let imageUrl;
      try {
        const data = typeof ret.data === 'string' ? JSON.parse(ret.data) : ret.data;
        imageUrl = data.ans || data.answer;
      } catch (e) {
        console.warn('解析响应数据失败:', e);
        imageUrl = ret.data; // 回退方案
      }

      if (!imageUrl) {
        throw new Error('未获取到有效图片URL');
      }

      setImgUrl(imageUrl);
      setStatus('生成完成');
    } catch (error) {
      console.error('生成错误:', error);
      setStatus(`生成失败: ${error.message}`);
    }
  };

  return (
    <div className='container'>
      <div className="input">
        <div className="file-input">
          <input 
            ref={fileRef} 
            type="file" 
            id='image' 
            name='image' 
            accept='image/*' 
            required 
            onChange={updateImageData}
          />
        </div>

        <img className="preview" src={imgPreview} alt='preview'/>

        <div className="settings">
          <div className="selection">
            <label>队服编号：</label>
            <input 
              type="number" 
              value={uniform_number}
              onChange={(e) => setUniformNumber(e.target.value)}
            />
          </div>
          <div className="selection">
            <label>队服颜色：</label>
            <select 
              value={uniform_color}
              onChange={(e) => setUniformColor(e.target.value)}
            >
              <option value="红">红</option>
              <option value="蓝">蓝</option>
              <option value="绿">绿</option>
              <option value="黄">黄</option>
              <option value="白">白</option>
              <option value="黑">黑</option>
            </select>
          </div>
        </div>

        <div className="settings">
          <div className="selection">
            <label>位置：</label>
            <select 
              value={position}
              onChange={(e) => setPosition(e.target.value)}
            >
              <option value="0">守门员</option>
              <option value="1">前锋</option>
              <option value="2">后卫</option>
            </select>
          </div>
          <div className="selection">
            <label>持杆：</label>
            <select 
              value={shooting_hand}
              onChange={(e) => setShootingHand(e.target.value)}
            >
              <option value="0">左手</option>
              <option value="1">右手</option>
            </select>
          </div>
          <div className="selection">
            <label>风格：</label>
            <select 
              value={style}
              onChange={(e) => setStyle(e.target.value)}
            >
              <option value="国漫">国漫</option>
              <option value="乐高">乐高</option>
              <option value="写实">写实</option>
              <option value="卡通">卡通</option>
              <option value="油画">油画</option>
              <option value="素描">素描</option>
            </select>
          </div>
        </div>

        <div className="generate">
          <button onClick={generate}>生成</button>
        </div>
      </div>

      <div className="output">
        <div className="generated">
          {imgUrl ? (
            <img src={imgUrl} alt="生成的图片" />
          ) : (
            <div className="placeholder">等待生成图片...</div>
          )}
          <div className="status">{status}</div>
        </div>
      </div>
    </div>
  );
}